﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AIController : ControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly string _ollamaApiUrl = "http://58.213.66.34:3008/v1/chat/completions"; // Ollama 本地 API

        public AIController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public class Message
        {
            [JsonProperty("role")]
            public string Role { get; set; } = "";

            [JsonProperty("content")]
            public string Content { get; set; } = "";
        }

        public class FunctionCall
        {
            [JsonProperty("name")]
            public string Name { get; set; }

            [JsonProperty("arguments")]
            public string Arguments { get; set; }
        }

        public class ChoiceMessage
        {
            [JsonProperty("role")]
            public string Role { get; set; }

            [JsonProperty("content")]
            public string Content { get; set; }

            [JsonProperty("function_call")]
            public FunctionCall FunctionCall { get; set; }
        }

        public class Choice
        {
            [JsonProperty("index")]
            public int Index { get; set; }

            [JsonProperty("message")]
            public ChoiceMessage Message { get; set; }

            [JsonProperty("finish_reason")]
            public string FinishReason { get; set; }
        }

        public class AIResponse
        {
            [JsonProperty("id")]
            public string Id { get; set; }

            [JsonProperty("object")]
            public string Object { get; set; }

            [JsonProperty("created")]
            public long Created { get; set; }

            [JsonProperty("model")]
            public string Model { get; set; }

            [JsonProperty("choices")]
            public List<Choice> Choices { get; set; }
        }

        public class ChatRequest
        {
            [JsonProperty("messages")]
            public List<Message> Messages { get; set; } = new();
        }

        [HttpPost("chat")]
        public async Task<ObjectResult> Chat([FromBody] ChatRequest request)
        {
            if (request == null || request.Messages == null || request.Messages.Count == 0)
                return new ObjectResult(new { success = false, message = "对话消息不能为空" });

            var httpClient = _httpClientFactory.CreateClient();

            // 1. 先请求模型，带函数定义
            var firstRequestBody = new
            {
                model = "deepseek-r1:14b",
                messages = request.Messages,
                functions = new[] {
                    new {
                        name = "getCurrentUserCount",
                        description = "获取当前系统在线人数",
                        parameters = new { type = "object", properties = new { } }
                    }
                },
                function_call = "auto"
            };

            var firstRequestJson = JsonConvert.SerializeObject(firstRequestBody);
            var content = new StringContent(firstRequestJson, Encoding.UTF8, "application/json");

            var firstResponse = await httpClient.PostAsync(_ollamaApiUrl, content);
            if (!firstResponse.IsSuccessStatusCode)
                return StatusCode((int)firstResponse.StatusCode, new { success = false, message = "本地 Ollama 服务不可用" });

            var firstResponseString = await firstResponse.Content.ReadAsStringAsync();

            AIResponse firstResponseData;
            try
            {
                firstResponseData = JsonConvert.DeserializeObject<AIResponse>(firstResponseString);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, message = "接口返回格式解析失败", detail = ex.Message });
            }

            if (firstResponseData?.Choices == null || firstResponseData.Choices.Count == 0)
                return StatusCode(500, new { success = false, message = "接口返回数据异常，缺少choices" });

            var firstChoice = firstResponseData.Choices[0];
            if (firstChoice.Message.FunctionCall != null)
            {
                // 2. 有函数调用，执行本地函数
                var functionName = firstChoice.Message.FunctionCall.Name;

                if (functionName == "getCurrentUserCount")
                {
                    int userCount = await GetUserCountAsync();

                    // 3. 用函数结果构造新的消息，继续请求模型
                    var newMessages = new List<Message>();
                    newMessages.AddRange(request.Messages);
                    newMessages.Add(new Message
                    {
                        Role = "function",
                        Content = userCount.ToString()
                    });

                    var secondRequestBody = new
                    {
                        model = "deepseek-r1:14b",
                        messages = newMessages
                    };

                    var secondRequestJson = JsonConvert.SerializeObject(secondRequestBody);
                    var secondContent = new StringContent(secondRequestJson, Encoding.UTF8, "application/json");

                    var secondResponse = await httpClient.PostAsync(_ollamaApiUrl, secondContent);
                    if (!secondResponse.IsSuccessStatusCode)
                        return StatusCode((int)secondResponse.StatusCode, new { success = false, message = "本地 Ollama 服务不可用" });

                    var secondResponseString = await secondResponse.Content.ReadAsStringAsync();

                    AIResponse secondResponseData;
                    try
                    {
                        secondResponseData = JsonConvert.DeserializeObject<AIResponse>(secondResponseString);
                    }
                    catch (Exception ex)
                    {
                        return StatusCode(500, new { success = false, message = "接口返回格式解析失败", detail = ex.Message });
                    }

                    if (secondResponseData?.Choices == null || secondResponseData.Choices.Count == 0)
                        return StatusCode(500, new { success = false, message = "接口返回数据异常，缺少choices" });

                    var finalReply = secondResponseData.Choices[0].Message.Content;
                    return Ok(new { success = true, reply = finalReply });
                }
                else
                {
                    return BadRequest(new { success = false, message = $"未知函数调用：{functionName}" });
                }
            }
            else
            {
                // 没有函数调用，直接返回内容
                var reply = firstChoice.Message.Content ?? "无回复内容";
                return Ok(new { success = true, reply });
            }
        }

        private async Task<int> GetUserCountAsync()
        {
            // TODO: 替换成你实际获取系统人数的逻辑
            await Task.Delay(10);
            return 123; // 示例返回固定人数
        }
    }
}
